package com.wish.g1.contract.controller;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bw.itext.pdf.service.PdfService;
import com.wish.g1.common.core.utils.StringUtils;
import com.wish.g1.common.core.utils.poi.ExcelUtil;
import com.wish.g1.common.core.web.controller.BaseController;
import com.wish.g1.common.core.web.domain.AjaxResult;
import com.wish.g1.common.core.web.page.TableDataInfo;
import com.wish.g1.common.log.annotation.Log;
import com.wish.g1.common.log.enums.BusinessType;
import com.wish.g1.common.security.annotation.RequiresPermissions;
import com.wish.g1.contract.entity.Contract;
import com.wish.g1.contract.service.IContractService;
import com.wish.g1.system.api.HouseFegin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hy-woo
 * @since 2022-11-21
 */
@Slf4j
@RestController
@RequestMapping("/contract")
public class ContractController  extends BaseController {
    @Autowired
    private IContractService contractService;

    @Autowired
    private HouseFegin houseFegin;

    @Autowired
    private PdfService pdfService;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String username;

    @Autowired
    KafkaTemplate kafkaTemplate;


    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("contract:contract:list")
    @GetMapping("/list")
    public TableDataInfo list(Contract contract)
    {
        startPage();
        QueryWrapper<Contract> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(contract.getSfContractNo())){
            wrapper.eq("sf_contract_no",contract.getSfContractNo());
        }
        if (StringUtils.hasText(contract.getPremiseName())){
            wrapper.eq("premise_name",contract.getPremiseName());
        }
        List<Contract> list = contractService.list(wrapper);
        return getDataTable(list);
    }

    /**
     * 查询房源列表
     */
    @RequiresPermissions("contract:contract:selHouse")
    @PostMapping("/selHouse")
    public TableDataInfo selHouse(){
        //远程调用房源列表
        TableDataInfo list = houseFegin.list();
        return getDataTable(list.getRows());
    }
    /**
     * pdf导出 线上合同
     */
    @RequiresPermissions("contract:contract:download")
    @PostMapping("/download")
    public void download(Integer id) throws IOException {
        Contract byId = contractService.getById(id);
        System.err.println("ID==========="+byId);

        List<Contract> list = Arrays.asList(byId);

        String fileName = "contract"+byId.getId()+".pdf";
        String pdfSignFileName = "newcontract"+byId.getId()+"pdf";

        pdfService.export(list,fileName,"测试pdf预览",Contract.class);
        pdfService.sign(fileName,pdfSignFileName);
        pdfService.download(pdfSignFileName,response);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("contract:contract:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Contract contract)
    {
        List<Contract> list = contractService.list();
        ExcelUtil<Contract> util = new ExcelUtil<Contract>(Contract.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     *业主管理
     */
    @RequiresPermissions("contract:contract:owner")
    @PostMapping("/owner")
    public TableDataInfo owner(Contract contract){
        startPage();
        QueryWrapper<Contract> wrapper = new QueryWrapper<>();
        wrapper.setEntity(contract);
        List<Contract> list = contractService.list(wrapper);
        return getDataTable(list);
    }

    /**
     * 解约合同查询
     */
    @RequiresPermissions("contract:contract:breakList")
    @GetMapping("/breakList")
    public TableDataInfo breakList(Contract contract){
        startPage();
        QueryWrapper<Contract> wrapper = new QueryWrapper<>();
        wrapper.setEntity(contract);
        List<Contract> list = contractService.breakList();
        return getDataTable(list);
    }


    /**
     * 获取【请填写功能名称】详细信息
     */
//    @RequiresPermissions("contract:contract:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(contractService.getById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @RequiresPermissions("contract:contract:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Contract contract)
    {
        //雪花算法生成合同编号
        Snowflake snowflake = IdUtil.getSnowflake();
        String idStr = snowflake.nextIdStr();
        //合同编号
        contract.setSfContractNo(idStr);
        //合同签订时间，（暂定设置为提交日期）
        contract.setConSignTime(new Date());
        //合合同录入时间，（暂定设置为提交日期）
        contract.setConInfoTime(new Date());
        //合同审核时间，（暂定设置为提交日期）
        contract.setConAudTime(new Date());
        return toAjax(contractService.save(contract));
    }

    /**
     * 修改【请填写功能名称】
     */
    @RequiresPermissions("contract:contract:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @RequestMapping("/edit")
    public AjaxResult edit(Integer id) {
        UpdateWrapper<Contract> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        wrapper.set("status", 2);
        wrapper.set("real_time", new Date());
        //创建邮件信息
        SimpleMailMessage message = new SimpleMailMessage();
        //设置发件人
        message.setFrom(username);
        //设置收件人
        message.setTo("2010468436@qq.com");
        //设置邮件主题
        message.setSubject("解约合同提醒");
        //设置邮件的内容体
        message.setText("解约成功");
        //设置邮件发送的时间
        message.setSentDate(new Date());
        //发送邮件
        javaMailSender.send(message);
        kafkaTemplate.send("wish", UUID.randomUUID().toString(),"解约成功");
        return toAjax(contractService.update(null, wrapper));
    }
    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("contract:contract:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(contractService.removeByIds(Arrays.asList(ids)));
    }

}
